from django.shortcuts import render,HttpResponse,reverse
from django.contrib.auth.hashers import make_password, check_password
from ..models import *
from django.http import JsonResponse
import os

#导入django自带的数据库表 User,Permission,Group
from django.contrib.auth.models import User,Permission,Group
#导入登录页退出模块
from django.contrib.auth import authenticate,login,logout
#回话处理模块
from django.contrib.auth.decorators import permission_required

# Create your views here.
def index(request):
    if request.method=="POST":
        #首页轮播图修改
        filename="banner"+request.POST.get('pid')+".jpg"
        myfile = request.FILES.get('pic', None)
        destination = open('./static/myhome/public/img/' + filename, "wb+")
        # 把文件切割成多个快
        for i in myfile.chunks():
            destination.write(i)

        destination.close()
    return render(request,'myadmin/index.html')

def user_log(request):
    return render(request,'myadmin/login.html')

def user_log_check(request):
    #print()
    #检测验证码
    if request.session.get('verifycode').upper()!=request.POST.get('vcode').upper():
        return HttpResponse('<script>alert("登录失败,验证码错误");location.href="/myadmin/user_log/";</script>')

    user=request.POST.get('username')
    pwd=request.POST.get('password')
    #传统验证
    # user_admin=Users.objects.filter(nikename=user,password=pwd).first()
    # if user_admin:
    #     request.session['user'] = user
    #django验证 走权限验证模块
    users=authenticate(request,username=user,password=pwd)
    if users is not None:
        login(request,users)
        request.session['user'] = {'username':users.username,'uid':users.id}
        return HttpResponse('<script>alert("登录成功");location.href="/myadmin/";</script>')
    else:
        return HttpResponse('<script>alert("登录失败");location.href="/myadmin/user_log/";</script>')
    #return HttpResponse('1')

def user_logout(request):
    del request.session['user']
    logout(request)
    return HttpResponse('<script>alert("退出成功");location.href="/myadmin/user_log/";</script>')


# 验证码
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')


#权限管理  管理员列表
@permission_required('auth.add_group',raise_exception=True)
def authuser_index(request):
    #获取所有的管理员
    data=User.objects.all()

    return render(request,"myadmin/auth_user.html",{"userdata":data})

#权限管理 管理员添加
@permission_required('auth.add_group',raise_exception=True)
def authuser_add(request):
    #获取当前已经创建的所有组
    gs=Group.objects.all()
    #默认没有创建组 所有是空集合
    print(gs)
    return render(request,"myadmin/authuser_add.html",{"grouplist":gs})

#权限管理 执行管理员添加
@permission_required('auth.add_group',raise_exception=True)
def authuser_insert(request):
    try:
        #接受表单数据
        data=request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        #接受到的关键字参数 现在不用所以删掉 在下面用的时候在重新获取
        data.pop('gs')
        #判断是否为超级管理员
        if data['is_superuser']=="1":
            #强制类型转换 否则会报错
            data['is_superuser']=True
            #创建超级管理员
            ob=User.objects.create_superuser(**data)
        else:
            #创建普通管理员
            ob=User.objects.create_user(**data)

        #获取后台传递过来的下拉列表框的内容  格式是列表
        gs=request.POST.getlist('gs')
        if gs:
            #设置管理员组
            ob.groups.set(gs)
            ob.save()
        return HttpResponse('<script>alert("创建成功");location.href="/myadmin/authuser_index"</script>')

    except:
        return HttpResponse('<script>alert("创建失败");location.href="/myadmin/authuser_index"</script>')

#权限组列表
@permission_required('auth.add_group',raise_exception=True)
def authgroup_index(request):
    #获取所有组
    groupdata=Group.objects.all()
    #分配数据
    return render(request,'myadmin/authgroup_index.html',{'groupdata':groupdata})

#新增用户组
@permission_required('auth.add_group',raise_exception=True)
def authgroup_insert(request):
    if request.method=="POST":
        #接受组名
        name=request.POST.get('name')
        print(name)
        #创建组
        g=Group(name=name)
        g.save()

        #给组设置权限  接受前台传来的 权限列表
        prms=request.POST.getlist('prms',None)
        if prms:
            #多对多关系 通过外检找到permissions 设置 第三张表
            g.permissions.set(prms)
            g.save()
        return HttpResponse('<script>alert("创建成功");location.href="/myadmin/authgroup_index"</script>')

    else:
        #获取所有的权限 推送到前台
        perms=Permission.objects.exclude(name__istartswith="Can")
        return render(request,'myadmin/authgroup_insert.html',{'perms':perms})
#用户组编辑
@permission_required('auth.add_group',raise_exception=True)
def authgroup_edit(request):
    #print(request)
    if request.method=='POST':
        id=request.POST.get('id')
        name=request.POST.get('name')
        g=Group.objects.get(id=id)
        g.name=name

        prms = request.POST.getlist('prms', None)
        if prms:
            # 多对多关系 通过外检找到permissions 设置 第三张表
            g.permissions.set(prms)
            g.save()
        return HttpResponse('<script>alert("更新成功");location.href="/myadmin/authgroup_index"</script>')

    else:
        id=request.GET.get('id')
        res=Group.objects.get(id=id)
        perms = Permission.objects.exclude(name__istartswith="Can")
        return render(request, 'myadmin/authgroup_edit.html', {'perms': perms,'group':res})

#管理员编辑
@permission_required('auth.add_group',raise_exception=True)
def authuser_edit(request):
    if request.method == 'POST':
        #pass

        try:
            # 接受表单数据
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')
            # 接受到的关键字参数 现在不用所以删掉 在下面用的时候在重新获取
            data.pop('gs')

            # 判断是否为超级管理员
            ob = User.objects.get(id=data['id'])
            ob.username=data['username']
            if data['password']:
                ob.password=make_password(data['password'])
            ob.email=data['email']
            if data['is_superuser'] == "1":
                # 强制类型转换 否则会报错
                data['is_superuser'] = True
                ob.is_superuser=data['is_superuser']
            ob.save()
            # 获取后台传递过来的下拉列表框的内容  格式是列表
            gs = request.POST.getlist('gs')
            if gs:
                # 设置管理员组
                ob.groups.set(gs)
                ob.save()
            return HttpResponse('<script>alert("更新成功");location.href="/myadmin/authuser_index"</script>')

        except:
           return HttpResponse('<script>alert("更新失败");location.href="/myadmin/authuser_index"</script>')

    else:
        id = request.GET.get('id')
        res = User.objects.get(id=id)
        return render(request, 'myadmin/authuser_edit.html', {'perms': Group.objects.all(), 'user': res})


@permission_required('auth.add_group', raise_exception=True)
#用户删除
def authuser_del(request):
    id=request.GET.get('id')
    try:
        ob=User.objects.get(id=id)
        if ob.username=='admin':
            return HttpResponse('<script>alert("删除失败,最高管理员不能被删除");location.href="/myadmin/authuser_index"</script>')
        ob.delete()
        return HttpResponse('<script>alert("删除成功");location.href="/myadmin/authuser_index"</script>')
    except:
        pass

    return HttpResponse('<script>alert("删除失败");location.href="/myadmin/authuser_index"</script>')

@permission_required('auth.add_group', raise_exception=True)
#权限组删除
def authgroup_del(request):
    id = request.GET.get('id')
    try:
        ob = Group.objects.get(id=id)
        ob.delete()
        return HttpResponse('<script>alert("删除成功");location.href="/myadmin/authgroup_index"</script>')
    except:
        pass
    return HttpResponse('<script>alert("删除失败");location.href="/myadmin/authgroup_index"</script>')
